<?php


namespace app\services\cupboard;


use app\models\cupboard\OperatorModel;
use app\services\area\RegionService;
use app\services\BaseService;
use think\facade\Db;

class OperatorService extends BaseService
{

    protected static function initModel()
    {
        return new OperatorModel();
    }

    /**
     * 获取运营商信息
     * @param $operatorId
     * @return array|mixed|\think\db\BaseQuery|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getOperatorInfo($operatorId)
    {
        $info = self::initModel()->find($operatorId);
        return $info;
    }

    /**
     * 运营商列表
     * @param $where
     * @param $page
     * @param $limit
     * @return array
     * @throws \think\db\exception\DbException
     */
    public static function getOperatorListService($where, $page, $limit)
    {
        $list = self::initModel()
            ->field('id,name,contact,phone,province,city,district,address,province_id,city_id,district_id')
            ->where($where)
            ->order('id', 'desc')
            ->paginate(['list_rows' => $limit, 'page' => $page])
            ->toArray();
        return $list;
    }

    /**
     * 保存信息
     * @param $id
     * @param $data
     * @return int|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function saveOperatorInfoService($id, $data)
    {
        $data['province'] = RegionService::getRegionName($data['province_id']);
        $data['city'] = RegionService::getRegionName($data['city_id']);
        $data['district'] = RegionService::getRegionName($data['district_id']);
        if (!$id) {
            $lastInfo = self::initModel()->order('id', 'desc')->find();
            unset($lastInfo['id']);
            $code = intval($lastInfo['code']) + 1;
            if ($code < 10) {
                $data['code'] = '00' . $code;
            } elseif ($code > 10 && $code < 100) {
                $data['code'] = '0' . $code;
            } else {
                $data['code'] = $code;
            }
            $data['created_at'] = date('Y-m-d H:i:s');
            $info = array_merge($lastInfo, $data);
            $res = self::initModel()->insert($info);
            return $res;
        } else {
            $data['updated_at'] = date('Y-m-d H:i:s');
            $res = self::initModel()->where('id', $id)->update($data);
            return $res;
        }
    }
}